package com.zhihuitong.meeting.base;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.CallSuper;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.listener.SimpleClickListener;
import com.zhihuitong.meeting.R;
import com.zhihuitong.meeting.view.stateview.StateView;

import java.util.List;


/**
 * 作者： lilingjie
 * 时间 2017/9/28.
 * 文件描述：
 * 版本号：V 1.0
 **/

public abstract class BaseListFragment<T, P extends BasePresenter> extends LazyLoadFragment {
    protected P mPresenter;
    private View mRootView;
    protected StateView mStateView;//用于显示加载中、网络异常，空布局、内容布局

    protected SwipeRefreshLayout mSwipeRefreshLayout;
    private FrameLayout mFrameLayout;

    protected RecyclerView mRecyclerView;
    protected BaseQuickAdapter<T, BaseViewHolder> mBaseQuickAdapter;

    private boolean isLazyLoadDone = false;//懒加载是否完成
    private boolean isCreateViewDone = false;//view是否初始化完成


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mPresenter = createPresenter();
    }

    protected abstract P createPresenter();


    /**
     * 搜索
     *
     * @param keyword
     */
    public void search(String keyword) {

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mRootView == null) {
            mRootView = inflater.inflate(R.layout.fragment_base_list, container, false);
            mSwipeRefreshLayout = (SwipeRefreshLayout) mRootView.findViewById(R.id.swipe_refresh_layout);
            mSwipeRefreshLayout.setEnabled(isRefreshEnable());
            mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    refresh();
                }
            });
            mSwipeRefreshLayout.setColorSchemeColors(getColorSchemeColors());
            mFrameLayout = (FrameLayout) mRootView.findViewById(R.id.fl_content);
            mStateView = StateView.inject(mRootView);
            addViewToContent(getContentView(), new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            afterCreateView(savedInstanceState);
        } else {
            mStateView = StateView.inject(mRootView);
            ViewGroup parent = (ViewGroup) mRootView.getParent();
            if (parent != null) {
                parent.removeView(mRootView);
            }
        }
        mStateView.setOnRetryClickListener(new StateView.OnRetryClickListener() {
            @Override
            public void onRetryClick() {
                refresh();
            }
        });
        return mRootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mPresenter != null) {
            mPresenter.detailView();
            mPresenter = null;
        }
        mRootView = null;
    }

    protected void afterCreateView(Bundle bundle) {
        isCreateViewDone = true;
        initData();
        init();
        initViews(bundle);
        onLazyLoad();
    }

    protected void initData() {

    }

    private void init() {
        initAdapter();

        mRecyclerView.setAdapter(mBaseQuickAdapter);

        mRecyclerView.setLayoutManager(getLayoutManager());
        mRecyclerView.addOnItemTouchListener(new SimpleClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                BaseListFragment.this.onItemClick(view, i, getEntity(i));
            }

            @Override
            public void onItemLongClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                BaseListFragment.this.onItemLongClick(view, i, getEntity(i));
            }

            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                BaseListFragment.this.onItemChildClick(view, i, getEntity(i));
            }

            @Override
            public void onItemChildLongClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                BaseListFragment.this.onItemChildLongClick(view, i, getEntity(i));
            }
        });
    }

    protected RecyclerView getRecyclerView() {
        return mRecyclerView;
    }

    protected BaseQuickAdapter<T, BaseViewHolder> getTBaseQuickAdapter() {

        return mBaseQuickAdapter;
    }

    private void initAdapter() {

        mBaseQuickAdapter = createBaseQuickAdapter();

        if (isLoadMoreEnable()) {
            mBaseQuickAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                @Override
                public void onLoadMoreRequested() {
                    loadMoreData(mBaseQuickAdapter.getData());
                }
            }, mRecyclerView);
        }
        mBaseQuickAdapter.setHeaderFooterEmpty(true, true);//没有数据的时候也显示头布局

        //设置没有数据的页面
       // mBaseQuickAdapter.setEmptyView(getEmptyViewResId(), mRecyclerView);
        //mBaseQuickAdapter.openLoadAnimation(getRecyclerViewLoadAnimation());
    }


    protected void initViews(Bundle bundle) {

    }

    protected void addViewToContent(View view, FrameLayout.LayoutParams layoutParams) {
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }
        mFrameLayout.addView(view, layoutParams);
    }

    /**
     * 获取填充内容,默认RecyclerView,子类可以重写
     *
     * @return
     */
    protected View getContentView() {
        if (mRecyclerView == null) {
            mRecyclerView = new RecyclerView(getActivity());
        }
        return mRecyclerView;
    }

    private int[] getColorSchemeColors() {
        return new int[]{Color.RED, Color.GREEN, Color.BLUE};
    }


    @CallSuper
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        //此方法 执行与 onCreateView之前
        super.setUserVisibleHint(isVisibleToUser);
        onLazyLoad();
    }

    /**
     * 当view 初始化完成 并且当前 fragment可见 并且懒加载没完成 执行此方法 加载数据
     */
    protected void onLazyLoad() {
        if (isCreateViewDone && getUserVisibleHint() && (!isLazyLoadDone)) {
            beginRefresh();
            isLazyLoadDone = true;
        }
    }

    /**
     * 开始刷新视图内容
     */
    public void beginRefresh() {
        mSwipeRefreshLayout.setRefreshing(true);
        refresh();
    }


    /**
     * 是否可刷新
     *
     * @return
     */
    protected boolean isRefreshEnable() {
        return true;
    }

    /**
     * 是否可以加载更多
     */
    public boolean isLoadMoreEnable() {
        return true;
    }

    /**
     * 设置是否可以加载更多
     */
    public void setLoadMoreEnable(boolean enable) {
        mBaseQuickAdapter.setEnableLoadMore(enable);
    }

    /**
     * 创建适配器
     *
     * @return
     */
    protected abstract BaseQuickAdapter<T, BaseViewHolder> createBaseQuickAdapter();

    /**
     * 刷新的方法
     */
    protected abstract void refresh();

    protected abstract void loadMoreData(List<T> data);


    /**
     * 没有数据的时候展示的layout
     */
    protected int getEmptyViewResId() {
        return R.layout.base_empty;
    }

    /**
     * 获取布局管理器,默认线性布局
     *
     * @return
     */
    protected RecyclerView.LayoutManager getLayoutManager() {
        return new LinearLayoutManager(getActivity());
    }

    /**
     * item动画效果
     */
    protected int getRecyclerViewLoadAnimation() {
        return BaseQuickAdapter.SLIDEIN_BOTTOM;
        // return 0;
    }

    /**
     * 加载数据完成 并且还有数据
     */
    @CallSuper
    protected void loadDataComplete() {
        mBaseQuickAdapter.loadMoreComplete();
        mSwipeRefreshLayout.setRefreshing(false);
    }

    /**
     * 加载数据完成 没有更多数据
     */
    @CallSuper
    protected void loadDataEnd() {
        mBaseQuickAdapter.loadMoreEnd();
        mSwipeRefreshLayout.setRefreshing(false);
    }

    /**
     * 加载数据失败
     */
    @CallSuper
    protected void loadDataFail() {
        mBaseQuickAdapter.loadMoreFail();
        mSwipeRefreshLayout.setRefreshing(false);
    }


    //adapter 相关操作
    protected T getEntity(int position) {
        return mBaseQuickAdapter.getItem(position);
    }

    protected void notifyItemChanged(int position) {
        mBaseQuickAdapter.notifyItemChanged(position);
    }

    protected void removeItem(int position) {
        mBaseQuickAdapter.remove(position);
    }

    /**
     * 添加数据到 recycler view 中
     */
    protected void addDataToRecyclerView(List<T> list) {
        mBaseQuickAdapter.addData(list);
        loadDataComplete();
    }

    protected void addData(List<T> list) {
        mBaseQuickAdapter.addData(list);
        loadDataComplete();
    }

    protected void addData(int position, T entity) {
        mBaseQuickAdapter.addData(position, entity);
        loadDataComplete();
    }

    protected void setNewData(List<T> list) {
        mBaseQuickAdapter.setNewData(list);
        mBaseQuickAdapter.disableLoadMoreIfNotFullPage(mRecyclerView);
        loadDataComplete();
    }


    //item 事件

    protected void onItemClick(View view, int position, T entity) {

    }

    protected void onItemLongClick(View view, int position, T entity) {

    }

    protected void onItemChildClick(View view, int position, T entity) {

    }

    protected void onItemChildLongClick(View view, int position, T entity) {

    }

}
